<template>
    <n-select
        :value="value"
        filterable
        placeholder="请输入用户名进行搜索"
        :options="userOptions"
        :loading="userLoading"
        clearable
        :multiple="multiple"
        remote
        max-tag-count="responsive"
        @search="searchChange"
        @update:value="(val, obj) => onChange(val, obj)"
    />
</template>
<script setup>
import { ref, computed, inject, toRefs } from "vue";
import { debounce } from "lodash";

const props = defineProps({
    value: {
        type: [Array, String],
        default: [],
    },
});
const emits = defineEmits(["update:value", "select"]);
const global = inject("global");

const userOptions = ref([]);
const userLoading = ref(false);

const { value } = toRefs(props);

const multiple = computed(() => {
    return Array.isArray(props.value) ? true : false;
});

const searchChange = debounce(function (val) {
    userSearch(val);
}, 500);

const userSearch = async (query) => {
    if (!query.length) {
        userOptions.value = [];
        return;
    }
    userLoading.value = true;
    let res = await global.$api.getUserList();
    userLoading.value = false;
    if (res.code === 200) {
        const { data } = res;
        data.map((v) => {
            v.label = v.name;
            v.value = v.id;
            return v;
        });
        userOptions.value = data;
    }
};

//筛选框改变
const onChange = (val, obj) => {
    emits("update:value", val);
    emits("select", val, obj);
};
</script>
